﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using mshtml;
using Encoder = System.Drawing.Imaging.Encoder;

namespace WindowsForms.Tests
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender1, EventArgs e1)
        {

            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, DateTime.Now.ToFileTime() + ".jpg");

            var url = textBox1.Text;


            var bmp = HtmlToImg.GetHtmlToImg(url, path);
           
            MessageBox.Show("生成图片:" + path); 
           // this.webBrowser1.DocumentCompleted += (s, e) => { richTextBox1.Text += "\r\nDocumentCompleted:" + e.Url; };
           // this.webBrowser1.Navigating += (s, e) => { richTextBox1.Text += "\r\nNavigating:" + e.Url; };
           // this.webBrowser1.Navigated += (s, e) => { richTextBox1.Text += "\r\nNavigated:" + e.Url; };
           //this.webBrowser1.Navigate(url);

            //PageToPDF2 to = new PageToPDF2();
            //to.OnEnd = o =>
            //    {
            //        MessageBox.Show("生成图片:" + path); 

            //    };
            //to.Begin(url, path, ImageFormat.Jpeg,this.webBrowser1); 
        }



    }
    
 
/// <summary>
/// 生成网页快照
/// </summary>
public class HtmlToImg
{
    private bool Ok;
    Bitmap m_Bitmap;
    string m_Url;
    string m_path; 
    
    public HtmlToImg(string Url, string path)
    {
        Ok = false;
        m_Url = Url;
        m_path = path;
    }
    public static bool GetHtmlToImg(string Url, string path)
    {

        HtmlToImg thumbnailGenerator = new HtmlToImg(Url, path);
        return thumbnailGenerator.GenerateHtmlToImgImage();
    }
    public bool GenerateHtmlToImgImage()
    {
        Thread m_thread = new Thread(new ThreadStart(_GenerateHtmlToImgImage));
        m_thread.SetApartmentState(ApartmentState.STA);
        m_thread.Start();
        m_thread.Join();
        return true;
    }
    private void _GenerateHtmlToImgImage()
    {
        WebBrowser m_WebBrowser = new WebBrowser();
        m_WebBrowser.ScrollBarsEnabled = false;
        m_WebBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
        m_WebBrowser.Navigated += m_WebBrowser_Navigated;
        m_WebBrowser.Navigate(m_Url);
        while (!Ok)
            Application.DoEvents();
        m_WebBrowser.Dispose();
    }

    void m_WebBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
    {
        WebBrowser m_WebBrowser = (WebBrowser)sender;
        var vDocument = (IHTMLWindow2)m_WebBrowser.Document.Window.DomWindow;
        vDocument.execScript("function confirm(str){return true;} ", "javascript"); //弹出确认
        vDocument.execScript("function alert(str){return true;} ", "javaScript");//弹出提示
    }
    private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
       
            WebBrowser m_WebBrowser = (WebBrowser) sender;  
            int width = m_WebBrowser.Document.Body.ScrollRectangle.Width + 2;
            int height = m_WebBrowser.Document.Body.ScrollRectangle.Height + 2;
            m_WebBrowser.ClientSize = new Size(width, height);
            m_WebBrowser.ScrollBarsEnabled = false;
            m_Bitmap = new Bitmap(m_WebBrowser.Bounds.Width, m_WebBrowser.Bounds.Height);
            m_WebBrowser.BringToFront();
            m_WebBrowser.DrawToBitmap(m_Bitmap, m_WebBrowser.Bounds);
            m_Bitmap = (Bitmap)m_Bitmap.GetThumbnailImage(width, height, null, IntPtr.Zero);

        using (MemoryStream stream = new MemoryStream())
        {
            m_Bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] buff = stream.ToArray(); 
            //保存图片
            using (FileStream fs = new FileStream(m_path, FileMode.Create))
            { 
                stream.WriteTo(fs);
                stream.Close();
                fs.Close();
            }
        }

        Ok = true;
       
    }
}
 
    public class PageToPDF2
    {
        // Fields
        private Bitmap bmp;
        private bool flag;
        private ManualResetEvent mre;
        public OnEndHandler OnEnd;
        private string path;
        private ImageFormat t;
        private string url;
        private WebBrowser wb;

        // Methods
        public PageToPDF2()
        {
            this.mre = new ManualResetEvent(false);
            this.url = "";
            this.path = "";

        }
        public void Begin(string url, string path, ImageFormat middleFormat, WebBrowser webBrowser)
        {
            this.flag = true;
            this.wb = webBrowser;
            this.wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(this.wb_DocumentCompleted);
            this.wb.Navigate(url);
            this.path = path;
            this.url = url;
            if (middleFormat == null)
            {
                this.t = ImageFormat.Jpeg;
            }
            else
            {
                this.t = middleFormat;
            }
        }

         




        private static ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            ImageCodecInfo[] imageEncoders = ImageCodecInfo.GetImageEncoders();
            for (int i = 0; i < imageEncoders.Length; i++)
            {
                if (imageEncoders[i].MimeType == mimeType)
                {
                    return imageEncoders[i];
                }
            }
            return null;
        }



        public string getExtName(string path)
        {
            int startIndex = path.LastIndexOf(".");
            return path.Substring(startIndex);
        }

         



        private void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {


            if (this.wb.ReadyState == WebBrowserReadyState.Complete)
            {
                int width = this.wb.Document.Body.ScrollRectangle.Width + 2;
                int height = this.wb.Document.Body.ScrollRectangle.Height + 2;
                this.wb.Size = new Size(width, height);
                this.wb.ScriptErrorsSuppressed = false;
                this.wb.ScrollBarsEnabled = false;
                width -= 0x10;
                this.bmp = new Bitmap(width + 10, height);
                Graphics.FromImage(this.bmp).Clear(Color.White);
                this.wb.DrawToBitmap(this.bmp, new Rectangle(0, 0, width, height));
                EncoderParameters encoderParams = new EncoderParameters(1);
                encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
                ImageCodecInfo encoderInfo = GetEncoderInfo("image/jpeg");
                this.bmp.Save(this.path, encoderInfo, encoderParams);
                this.bmp.Clone();
                
                if (this.OnEnd != null)
                {
                    this.OnEnd(null);
                }
            }
        }

 

 


        // Nested Types
        public delegate void OnEndHandler(object o);
    }


}
